package cn.com.surker.system.service.impl;

import cn.com.surker.common.Constant;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.dao.SysOriginDao;
import cn.com.surker.system.dao.SysUserDao;
import cn.com.surker.system.entity.SysOrigin;
import cn.com.surker.system.entity.SysUser;
import cn.com.surker.system.service.IErpOriginService;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author luotao
 * @date 2022/11/1
 */
@Service
public class ErpOriginServiceImpl extends ServiceImpl<SysOriginDao, SysOrigin> implements IErpOriginService {

	@Resource
	private SysOriginDao sysOriginDao;
	@Resource
	private SysUserDao sysUserDao;
	@Resource
	private DataSourceInfoDao dsDao;

	@Override
	public List<SysOrigin> relationOriginList(Long originId) {
		List<Long> originIds = null;
		if(originId != null){
			originIds = new ArrayList<>();
			originIds.add(originId);
		}
		List<SysOrigin> sysOrigins = relationOriginList(originIds);
		return sysOrigins;
	}


	/**
	 * 根据ID查询部门
	 * @param id
	 * @return
	 */
	public SysOrigin queryById(Long id) {
		if (StringUtils.isNull(id))
			return null;

		SysOrigin origin = sysOriginDao.selectById(id);
		if (origin == null)
			return null;

		return origin;
	}

	@Override
	public List<SysOrigin> relationOriginList(List<Long> originIds) {
		List<SysOrigin> sysOrigins = sysOriginDao.queryRelationOrigin(originIds);
		return sysOrigins;
	}

	@Override
	public List<SysOrigin> relationUserOrgList(Long userId) {
		if(userId == null){
			return new ArrayList<>();
		}
		/*// 查询所有的部门
		QueryWrapper<SysOrigin> orgp = new QueryWrapper<>();
		orgp.eq("status",StateEnum.ENABLED.getCode());
		List<SysOrigin> allOrgs = sysOriginDao.selectList(orgp);
		// 查询用户关联的站点(注意，是站点，不是集团和部门)
		List<SysOrigin> userOrgs = sysOriginDao.queryByUidAllOrigin(userId);
		// 从全部站点中查询出用户关联站点下的各个部门,
		if(userOrgs != null && !userOrgs.isEmpty()){
			for(SysOrigin origin : userOrgs){
				List<SysOrigin> child = getChild(origin,allOrgs);
				origin.setChildren(child);
			}
			SysOrigin groupOrg = new SysOrigin();
			groupOrg.setId(1l);
			groupOrg.setType(Constant.ORG_TYPE_GROUP);
			groupOrg.setOriginName("驰旭集团");
			groupOrg.setChildren(userOrgs);
			List<SysOrigin> so = new ArrayList<>();
			so.add(groupOrg);
			return so;
		}else {
			return new ArrayList<>();
		}*/
		// 查询用户关联的站点(注意，是站点，不是集团和部门)
		List<SysOrigin> userOrgs = sysOriginDao.queryByUidAllOrigin(userId);
		if(userOrgs != null && !userOrgs.isEmpty()){
			// 取出该用户的全部id信息
			List<Long> ids = userOrgs.stream().filter(i -> {
				Long id = i.getId();
				if (id != null) {
					return true;
				} else {
					return false;
				}
			}).map(SysOrigin::getId).collect(Collectors.toList());
			List<SysOrigin> userAllOrgs = relationOriginList(ids);
			if(userAllOrgs != null){
				// 设置集团参数（所有的部门都应该是集团下的，但是管理站点本身不关联集团）
				SysOrigin groupOrg = new SysOrigin();
				groupOrg.setId(1l);
				groupOrg.setType(Constant.ORG_TYPE_GROUP);
				groupOrg.setOriginName("驰旭集团");
				groupOrg.setChildren(userAllOrgs);
				List<SysOrigin> so = new ArrayList<>();
				so.add(groupOrg);
				return so;
			}else {
				return userAllOrgs;
			}
		}else {
			return new ArrayList<>();
		}
	}

	@Override
	public List<SysUser> relationOriginUserList(Long orgId, String name, String phone, Integer status) {
		List<SysUser> users = new ArrayList<>();
		// 获取部门信息
		if (orgId == null){
			// 没有选中部门，默认查全部
			users = sysUserDao.queryUserByOrgIds(null,name,phone,status);
			return users;
		}
		SysOrigin sysOrigin = sysOriginDao.selectById(orgId);
		if(sysOrigin == null || StateEnum.DISABLED.getCode() == sysOrigin.getStatus()){
			// 没有站点信息
			return users;
		}
		if(sysOrigin.getType() == Constant.ORG_TYPE_GROUP){
			// 集团查询全部
			users = sysUserDao.queryUserByOrgIds(null,name,phone,status);
		}else {
			// 如果不是集团，查询部门下的所有部门
			List<SysOrigin> origins = relationOriginList(orgId);
			if(origins != null && !origins.isEmpty()){
				List<Long> orgIds = new ArrayList<>();
				for(SysOrigin origin : origins){
					// 添加本级别id
					List<Long> tids = relaOrgIds(origin);
					if(tids != null && !tids.isEmpty()){
						orgIds.addAll(tids);
					}
				}
				users = sysUserDao.queryUserByOrgIds(orgIds, name, phone, status);
			}
		}
		return users;
	}

	@Override
	public List<SysUser> relationOriginUserList(SysOrigin origin, String name, String phone, Integer status) {
		List<SysUser> users;
		// 获取部门信息
		if (origin == null){
			// 没有选中部门，默认查全部
			users = sysUserDao.queryUserByOrgIds(null,name,phone,status);
			return users;
		}
		List<Long> orgIds = relaOrgIds(origin);
		users = sysUserDao.queryUserByOrgIds(orgIds, name, phone, status);
		return users;
	}

	@Override
	public List<SysUser> relationOriginUserList(List<SysOrigin> orgs, String name, String phone, Integer status) {
		List<SysUser> users;
		// 获取部门信息
		if (orgs == null || orgs.isEmpty()){
			// 没有选中部门，默认查全部
			users = sysUserDao.queryUserByOrgIds(null,name,phone,status);
			return users;
		}
		List<Long> orgIds = new ArrayList<>();
		for(SysOrigin origin : orgs){
			// 添加本级别id
			List<Long> tids = relaOrgIds(origin);
			if(tids != null && !tids.isEmpty()){
				orgIds.addAll(tids);
			}
		}
		users = sysUserDao.queryUserByOrgIds(orgIds, name, phone, status);
		return users;
	}

	@Override
	public List<Map<String, Object>> userPositionOrg(Long userId) {
		if(userId == null){
			return new ArrayList<>();
		}
		List<Map<String,Object>> res = new ArrayList<>();
		List<Map<String,Object>> userPosList = sysUserDao.userPosition(userId);
		if(userPosList != null && !userPosList.isEmpty()){
			for(int i = 0,s = userPosList.size();i < s;i++){
				Map<String, Object> map = userPosList.get(i);
				/*// 此处的orgid 为 用户岗位表中的id,对应的是该岗位的最新组织机构,通常为部门
				Object orgId = map.get("orgId");
				List<Map<String,Object>> orgs = new ArrayList<>();
				if(orgId != null && orgId instanceof Long){
					// 迭代查询父级组织机构
					SysOrigin origin = sysOriginDao.relationParentOrigin(Long.valueOf(orgId.toString()));
					relationParentOrg(orgs,origin);
				}
				map.put("orgs",orgs);*/
				Object originObj = map.get("origin");
				List<Map<String,Object>> orgs = new ArrayList<>();
				if(originObj != null && originObj instanceof SysOrigin){
					SysOrigin origin = (SysOrigin)originObj;
					relationParentOrg(orgs,origin);
				}
				map.remove("origin");
				map.put("orgs",orgs);
				res.add(map);
			}
		}
		return res;
	}

	@Override
	public List<SysOrigin> findAll(SysOrigin dto) {
		QueryWrapper<SysOrigin> query = new QueryWrapper();
		if(dto != null){
			if (!StringUtils.isNull(dto.getType()))
				query.eq("type", dto.getType());
			if(dto.getId() != null){
				query.eq("id",dto.getId());
			}
			if(dto.getPid() != null){
				query.eq("pid",dto.getPid());
			}
			if (StringUtils.isNotBlank(dto.getOriginName())){
				query.eq("origin_name",dto.getOriginName());
			}
		}
		query.eq("status",StateEnum.ENABLED.getCode());
		query.orderByAsc("sortby");
		List<SysOrigin> list = sysOriginDao.selectList(query);
		return list;
	}

	/**
	 * 查询用户所属站点
	 * @return
	 */
	@Override
	public List<Map<String, Object>> findUserOrigin(Integer type, Integer status, Long uid) {
		List<Map<String, Object>> list = sysOriginDao.queryUserCompanyById(type, status, uid);
		if (list == null || list.size() == 0)
			list = sysOriginDao.queryUserOrigin(type, status);
		return list;
	}

	private void relationParentOrg(List<Map<String,Object>> orgs, SysOrigin origin) {
		if(origin != null){
			Map<String,Object> org = new HashMap<>();
			Long id = origin.getId();
			String originName = origin.getOriginName();
			org.put("orgId",id);
			org.put("orgName",originName);
			orgs.add(org);
			SysOrigin parent = origin.getParent();
			relationParentOrg(orgs,parent);
		}
	}


	/**
	 * 根据用户名查询用户关联站点
	 * @param uid
	 * @return
	 */
	@Cacheable(cacheNames = "userRelationOrigin", key = "#uid")
	public List<SysOrigin> queryByUidOrigin(Long uid) {
		if (StringUtils.isNull(uid))
			return null;

		List<SysOrigin> list = sysOriginDao.queryByUidAllOrigin(uid);
		if (list == null || list.size() == 0)
			return null;

		return list;
	}

	@Override
	public List<Long> relaOrgIds(List<SysOrigin> origins) {
		List<Long> orgIds = new ArrayList<>();
		for(SysOrigin origin : origins){
			// 添加本级别id
			List<Long> tids = relaOrgIds(origin);
			if(tids != null && !tids.isEmpty()){
				orgIds.addAll(tids);
			}
		}
		return orgIds;
	}

	private List<Long> relaOrgIds(SysOrigin origin){
		List<Long> ids = new ArrayList<>();
		if(origin == null){
			return ids;
		}
		// 添加本级id
		if(origin.getType() != Constant.ORG_TYPE_GROUP){
			// 集团的不添加
			Long id = origin.getId();
			ids.add(id);
		}
		List<SysOrigin> children = origin.getChildren();
		// 添加下级id
		if(children != null){
			for (SysOrigin co : children){
				List<Long> cids = relaOrgIds(co);
				ids.addAll(cids);
			}
		}
		return ids;
	}

	/**
	 * 设置子集部门
	 * @param porg
	 * @param allOrgs
	 * @return
	 */
	private List<SysOrigin> getChild(SysOrigin porg, List<SysOrigin> allOrgs) {
		List<SysOrigin> childs = allOrgs.stream().filter(i -> {
			if (i.getPid() != null && i.getPid().equals(porg.getId())) {
				return true;
			} else {
				return false;
			}
		}).collect(Collectors.toList());
		if(childs != null && !childs.isEmpty()){
			for(SysOrigin c : childs){
				List<SysOrigin> child2 = getChild(c, allOrgs);
				if(child2 != null && !child2.isEmpty()){
					c.setChildren(child2);
				}
			}
		}
		return childs;
	}

	public SysOrigin queryOrgByDept(Long deptId){
		if(deptId == null){
			return null;
		}
		SysOrigin origin = sysOriginDao.relationParentOrigin(deptId);
		SysOrigin so = relaParentOrg(origin);
		return so;
	}

	@Override
	public List<SysOrigin> findDepts(Long parentOrgId,Long userId) {
		if (userId == null || parentOrgId == null){
			return new ArrayList<>();
		}
		List<SysOrigin> depts = sysOriginDao.findDepts(userId, parentOrgId);
		return depts;
	}


	/**
	 * 检查用户是否关联数据源
	 * @param uid
	 * @return
	 */
	public Integer checkUserData(Long uid) {
		if (StringUtils.isNull(uid))
			return 0;
		Integer total = dsDao.queryUidByData(uid);
		if (total > 0)
			return 1;
		return 0;
	}

	private SysOrigin relaParentOrg(SysOrigin origin){
		if(origin != null){
			SysOrigin parent = origin.getParent();
			if(parent == null){
				return origin;
			}else {
				return relaParentOrg(parent);
			}
		}else {
			return null;
		}
	}
}
